<script setup lang="ts">
import { useLocalStore } from "@/views/inspection-plan/line/store";
import { LPolyline, LCircle, LMarker } from "@vue-leaflet/vue-leaflet";
import { useMap } from "@/views/inspection-plan/line/components/Map/index.vue";

const store = useLocalStore();
const { jsonLine } = storeToRefs(store);
const latlngsRef = ref();
const { L }: any = window;
const getDivIcon = (name) =>
  L.divIcon({
    html:
      `<span style="width: 40px;display: inline-block;background: #18998d;padding: 5px 8px;\n` +
      `border-radius: 10px;color: #fff;position: relative;top:-30px;left: -10px;">${name}</span>`,
    bgPos: [40, 20],
    className: "divIcon",
  });

watchEffect(() => {
  if (jsonLine.value) {
    const map = useMap();
    try {
      const { coordinates } = JSON.parse(jsonLine.value);
      if (coordinates.length === 2 && Number.isFinite(coordinates[0])) {
        const [x, y] = coordinates;
        map.setView([y, x], 18);
        latlngsRef.value = [[y, x]];
      } else if (coordinates.length > 0) {
        const latlngs = coordinates.map((item) => [...item].reverse());
        if (coordinates.length > 1) {
          const bounds = L.polyline(latlngs).getBounds();
          map.fitBounds(bounds);
        } else if (coordinates.length === 1) {
          const center = latlngs[0];
          map.setView(center, 18);
        }
        latlngsRef.value = latlngs;
      } else {
        latlngsRef.value = null;
      }
    } catch (e) {}
  } else {
    latlngsRef.value = null;
  }
});
</script>

<template v-if="latlngsRef">
  <LPolyline
    v-if="latlngsRef?.length > 1"
    :lat-lngs="latlngsRef"
    weight="4"
    color="green"
  />
  <LCircle
    v-for="latlng in latlngsRef"
    :key="latlng"
    :lat-lng="latlng"
    color="red"
    radius="3"
  />
  <LMarker
    v-if="latlngsRef"
    :lat-lng="latlngsRef[0]"
    :icon="getDivIcon('起点')"
  />
  <LMarker
    v-if="latlngsRef?.length > 1"
    :lat-lng="latlngsRef[latlngsRef.length - 1]"
    :icon="getDivIcon('终点')"
  />
</template>

<style scoped lang="scss"></style>
